<template>
  <div class="app-container">
    <el-form
      :model="ebook"
      :rules="rules"
      ref="ruleForm"
      label-width="200px"
      class="demo-ruleForm"
    >
      <el-form-item label="所属科目">
        <el-select v-model="ebook.subjectId" placeholder="请选择">
          <el-option
            v-for="item in subjects"
            :key="item.id"
            :label="item.subjectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电子书名" prop="ebookUrl">
        <el-input v-model="ebook.bookName" maxlength="20" show-word-limit>
          <template slot="prepend">《</template>
          <template slot="append">》</template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="电子书作者"
        prop="bookAuthor"
        maxlength="10"
        show-word-limit
      >
        <el-input v-model="ebook.bookAuthor"></el-input>
      </el-form-item>
      <el-form-item class="myuploader" label="电子书封面" prop="bannerImg">
        <el-upload
          ref="uploader_img"
          class="upload-demo"
          :on-change="handleImgChange"
          :action="uploadUrl"
          :file-list="imgList"
          :multiple="false"
          :auto-upload="false"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="电子书简介" prop="bookInfo">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入电子书简介"
          v-model="ebook.bookInfo"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="电子书描述" prop="bookRemarks">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入电子书描述"
          v-model="ebook.bookRemarks"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="myuploader" label="电子书文件" prop="bannerImg">
        <el-upload
          ref="uploader_file"
          class="upload-demo"
          :on-change="handleFileChange"
          :action="uploadUrl"
          :file-list="fileList"
          :multiple="false"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传txt文件，且不超过2MB
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="电子书价格" prop="price">
        <el-input v-model="ebook.price" @change="handlePriceChange"></el-input>
      </el-form-item>
      <el-form-item label="显示排序" prop="orderNum">
        <el-input-number
          v-model="ebook.orderNum"
          :min="1"
          :max="999"
          label="排序号"
        ></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addEBookApi } from "@/api/ebook";
import { getAllSubjectApi } from "@/api/subject";
export default {
  data() {
    return {
      imgList: [],
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/ebook",
      ebook: {
        userId: 1,
        price: 0,
        orderNum: 1,
      },
      subjects: [],
      rules: {
        bookName: [
          { required: true, message: "请输入电子书名", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "请输入排序号", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
      },
    };
  },
  created() {
    getAllSubjectApi().then((response) => {
      this.subjects = response.data;
    });
  },
  methods: {
    uploadSectionFile() {
      /** 电子书封面检查 */
      if (this.imgList.length <= 0) {
        this.$message.error("电子书封面不能为空");
        return;
      }
      const img = this.imgList[0].raw;
      /** 电子书文件检查 */
      if (this.fileList.length <= 0) {
        this.$message.error("电子书文件不能为空");
        return;
      }
      const file = this.fileList[0].raw;
      // 根据后台需求数据格式
      const form = new FormData();
      // 电子书封面对象
      form.append("image", img);
      //电子书文本文件
      form.append("file", file);
      //遍历eobbok转formdata格式键值对
      Object.keys(this.ebook).forEach((key) => {
        form.append(key, this.ebook[key]);
      });
      addEBookApi(form).then((response) => {
        if (this.status == 0) {
          this.$message("提交成功");
        }
        this.$router.push("/content/ebook");
      });
    },
    handleFileChange(file, fileList) {
      const isTxt = file.raw.type === "text/plain";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (fileList.length > 0) {
        if (!isTxt) {
          this.$message.error("上传文件只能是 TXT 格式!");
          this.fileList = [];
          return false;
        } else if (!isLt2M) {
          this.$message.error("上传文件大小不能超过 2MB!");
          this.fileList = [];
          return false;
        }
        //单个覆盖上传
        this.fileList = [fileList[fileList.length - 1]];
        return true;
      }
    },
    handleImgChange(file, fileList) {
      const isPNG = file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 0.5;
      if (fileList.length > 0) {
        if (!isPNG) {
          this.$message.error("上传图片只能是 PNG 格式!");
          this.imgList = [];
          return false;
        } else if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 500KB!");
          this.imgList = [];
          return false;
        }
        //单个覆盖上传
        this.imgList = [fileList[fileList.length - 1]];
        return true;
      }
    },
    handlePriceChange() {
      if (isNaN(this.ebook.price)) {
        this.ebook.price = 0.0;
      }
    },
    submitForm(formName) {
      if (this.fileList.length <= 0 || this.imgList.length <= 0) {
        this.$message("请选择封面和文件");
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadSectionFile();
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
.myuploader >>> .el-list-enter-active,
.myuploader >>> .el-list-leave-active {
  transition: none;
}

.myuploader >>> .el-list-enter,
.myuploader >>> .el-list-leave-active {
  opacity: 0;
}
</style>